const EFFECT_LEVEL = 1;
const PAGE_WIDTH = 1900;
const PAGE_HEIGHT = 3648;
const PAGE_BR_VH = 3.5;

var _isMobile=false;
/* br:108 */
var MODEL={width:1900,height:3648,outerSpacing:100*2,pageBorderRadius:84*2};
var currentProject={
	displayLens:true,
	modelClass:'model_white',
	svg_time_black:"images/1436-email-black.svg",
	svg_swb_black:"images/swb-40-black.svg",
	svg_time_white:"images/1436-email-white.svg",
	svg_swb_white:"images/swb-40-white.svg",
	svg_camera:'images/camera-short.png',
    time_i2cons:['images/topbar_icons/bilibili.png','images/topbar_icons/x.jpg']
};
function GetTopBar(color){
	if(!color){color="black";}

	var r={};
	if(color=="white"){
		r['time']=currentProject.svg_time_white;
		r['swb']=currentProject.svg_swb_white;
	}else{
		r['time']=currentProject.svg_time_black;
		r['swb']=currentProject.svg_swb_black;
	}
	r['camera']=currentProject.svg_camera;
	return r;

}



var nav={
	items:[
		{title:'全部分类'},
		{title:'小说类',projects:['小说类','橘子小说']},
		{title:'工具类',model:'model_black',projects:['BitTorrent']},
		{title:'商城类',projects:['EShop']},
		{title:'其它',projects:['易速招聘']}
	],
	active:0,
};
function GetProjectIndexByCategory(title){
	var r=-1,i=0;
	for(let x of nav.items){
		if(x.title == title){
			r=i;
			break;
		}
		i++;
	}
	return r;
}

var pages=[];
var _flagFirstInit=true;
function RandomArrayItems(ar){
	if(!ar){return null;}
	var flags=[];
	var newar=[];
	for(var i=0;i<ar.length;i++){
		flags.push(i);
	}
	while(1){
		if(flags.length<1){break;}
		var n = flags.length;
		var i=0;
		if(1==n){
			var realIndex = flags[i];
			newar.push(ar[realIndex]);
			break;
		}
		var i = zRandomRangeI(0, flags.length-1);
		var realIndex = flags[i];
		newar.push(ar[realIndex]);
		flags.splice(i, 1);
	}
	return newar; 
}
var _allPages=[];
function OnSwitchProject(index){
	console.log('OnSwitchProject:',index);
	pages=null;
	pages=[];
	if(index == 0){
		if(_isMobile){
			 for(let p of _pages){
			 	pages.push(p);
			 }
		}else{
			if(_flagFirstInit){
				//console.log(_pages);
				_flagFirstInit = false;
				_allPages = RandomArrayItems(_pages);
			}
			pages = _allPages;
		} 
	}else{
		var t = nav.items[index];
		for(let p of _pages){
			if(t.projects.indexOf(p.project)>=0){
				pages.push(p);
			}
		}
	} 
	var cp = nav.items[index];
	if(cp.model){
		currentProject.modelClass = cp.model;
	}else{
		currentProject.modelClass = 'model_white';
	}

	$("#pages").html(" ");
	LoadImages();

	var xml=`<div style="width:20vh;height:20vh;min-width:20vh;min-height:20vh;background:none;"></div>`;
	$("#pages").append(xml);
	sb01.SetPosition(0);
	//localStorage.clear();
	//console.log(localStorage.length);
	//console.log("setPI:",index);
	//var r=localStorage.setItem("pi2323",''+index);
	//console.log(r);
	// STORAGE.setNumber("projectIndex",index);
}
function MakeImageUrl(url){
	var newurl=url;
	if(!strhas(url,'/')){
		newurl = 'show/'+url;
	}
	if(!strhas(newurl,".jpg") && !strhas(newurl,".png")){
		newurl += ".png";
	}
	return newurl;
}
function FormatPages(){
	var i=0;
	for(let x of _pages){
		x['index']=i;
		i++;
		if(!strhas(x.url,"/")){
			x.url = MakeImageUrl(x.url);
			if(x.upper){
				x.upper = MakeImageUrl(x.upper);
			}
			if(x.lower){
				x.lower = MakeImageUrl(x.lower);
			}
			if(!x.project){
				x.project="default";
			} 
		}
		if(x.bottomnav){
			if(x.bottomnav.bg){ 
				var mcc = zMaxColorChannel(x.bottomnav.bg);
				if(mcc < 80){
					x.bottomnav['color']='white';
				}else{
					x.bottomnav['color']='black';
				} 
			}
		}
	} 
	
}
var _active_index=0;
function FindUrl(url){
	var r=-1,i=0;
	for(let x of pages){
		if(x.url == _current_url){
			r=i;
			break;
		}
		i++;
	}
	return r;
}
function FindPageFullUrl(targeturl){
	var ns = targeturl;
	if(targeturl.indexOf('%')>0){
		ns = decodeURI(ns);
	}
	var r=-1,i=0;
	for(let x of pages){
		if(ns.indexOf(x.url) >= 0){
			r=i;
			break;
		}
		i++;
	}
	return r;
}

var scrollBarAdjustProps=[];
var sbid = 'mysb01';


function CScrollBar(id,scrollParentID,scrollContentID){
	this.id = id;
	this.id_outer = id+'_parent';
	this.obj = $("#"+id);
	this.parent = $("#"+this.id_outer);
	this.scrollParent = $("#"+scrollParentID);
	this.scrollContent = $("#"+scrollContentID);

	this.SetColor=function(c){
		var obj = document.getElementById(this.id);
		obj.style.background='#4169E1';
	};
	this.GetParentWidth=function(){
		var pw = this.scrollParent.width();
		return pw;
	};
	this.GetContentWidth=function(){
		var cw = this.scrollContent.prop('scrollWidth');
		return cw;
	};
	this.GetMaxScrollLeft=function(){
		var left = this.scrollContent.prop('scrollWidth') - this.scrollParent.width();
		return left;
	};
	/* 0.0 ~ 1.0 */
	this.SetPositionF=function(f){
		if(f<0){f=0;}
		else if(f>1){f=1;}
		var pos = this.parent.width() - this.obj.width();
		this.SetPosition(pos * f);
	};
	this.SetPosition=function(pos){
		if(pos<0){pos=0;}
		var maxPos = this.parent.width() - this.obj.width();
		if(pos > maxPos){
			pos = maxPos;
		}
		this.obj.css("margin-left",pos+'px');
		var schedule = pos / maxPos;
		var pw = this.GetParentWidth();
		var cw = this.GetContentWidth();
		if(cw > pw){
			var lessw = cw - pw; 
			var obj = document.getElementById(scrollContentID);
			obj.scrollLeft = lessw * schedule;
		} 
	};

}
var sb01 = new CScrollBar('mysb01','pages_outer','pages');

function InitScrollBar(outerID,innerID){
	var obj = document.getElementById(innerID);
	scrollBarAdjustProps[innerID+'parent']=outerID;
	//var left = $("#"+outerID).css('left');
	//console.log("left:",left);

	obj.addEventListener("mousedown",e=>{
		const rect = obj.getBoundingClientRect();
		const offx = e.clientX - rect.left;  
		scrollBarAdjustProps[innerID+'offsetx']=offx; 
		scrollBarAdjustProps[innerID+'down']=true;
		scrollBarAdjustProps['adjusting']=innerID;  
		$("#"+innerID).css("background","linear-gradient(to right,#FF9900 0%,#00FFFF 100%)");
		e.preventDefault(); 
		e.stopPropagation();
	}); 
	var outerObj = document.getElementById(outerID);
	outerObj.addEventListener("mousedown",e=>{
		const rect = outerObj.getBoundingClientRect();
		var offx = e.clientX - rect.left;
		var offy = e.clientY - rect.top;  
		offx -= scrollBarAdjustProps[innerID+'offsetx'];
		sb01.SetPosition(offx);
	});
}

document.addEventListener("mousemove",e=>{
	if(scrollBarAdjustProps['adjusting']){
		var currentID = scrollBarAdjustProps['adjusting'];
		var pid = scrollBarAdjustProps[currentID+'parent'];
		var pr = GetClientRect(pid); 
		var mousex = e.clientX; 
		const mouseOffsetX = mousex - scrollBarAdjustProps[currentID+'offsetx'] - pr.left;
		//SetScrollBarPosititonX(currentID, mouseOffsetX);  
		sb01.SetPosition(mouseOffsetX);
	}
});
document.addEventListener("mouseup",e=>{
	flagDownPage = null;
	if(scrollBarAdjustProps['adjusting']){
		var id = scrollBarAdjustProps['adjusting'];
		scrollBarAdjustProps['adjusting']=null;  
		$("#"+id).css("background","#fff");
	} 
});
InitScrollBar("mysb01_parent","mysb01");

let uicScrollViewIsDown = false;
let uicScrollViewStartX;
let uicScrollViewLeft;

function SetupAutoHideTopbar(pageKey){
	var majorpage = document.getElementById("MajorPage"+pageKey);
	if(majorpage){ 
		majorpage.addEventListener('scroll',function(event){
			var id = event.currentTarget.id;
			var obj = document.getElementById(id);
			if(obj){
				var y = obj.scrollTop;
				if(y > 0){
					//$("#"+id+"topbar").hide(); 
					$("#"+id+"swb").hide();
					$("#"+id+"time").hide();
				}else{
					//$("#"+id+"topbar").show();
					$("#"+id+"swb").show();
					$("#"+id+"time").show();
				}
			}
		});
	}
}

function ZoomPreviewByPageID(id){
	var i = ExtractIntFromString(id,-1);
	if(-1 != i){
		Event_ZoomPreview(i);
	} 
}
function ScrollXByLButtonDrag(id){  
	if(!id){return false;}
	var container = document.getElementById(id);
	if(!container){return false;}
	
	var pageDownX=0;
	var pageDownY=0;
	var flagDownPage = null;
	var downTime =0;
	
	container.addEventListener('mousedown', e=> {
		uicScrollViewIsDown = true;
		uicScrollViewStartX = e.pageX - container.offsetLeft;
		uicScrollViewLeft = container.scrollLeft;
		$("#"+id).css("cursor","grabbing");
		var eid = e.target.id; 
		if(eid && e.button==0){
			if(eid.indexOf("MajorPage")>=0){
				pageDownX = e.clientX;
				pageDownY = e.clientY;
				flagDownPage = e.target.id;
				downTime = Date.now(); 
			}
		} 
		e.preventDefault(); 
		e.stopPropagation();
	});
	container.addEventListener('mouseleave', e=> {
		uicScrollViewIsDown = false; 
	});
	container.addEventListener('mouseup', e=> {
		if(flagDownPage && e.button==0){
			var t = Date.now();
			var errTime = t - downTime;
		 
			var dx = e.clientX - pageDownX;
			var dy = e.clientY - pageDownY;
			var dist = Math.sqrt(dx*dx+dy*dy); 
			if(errTime < 400 && dist <= 1){
				ZoomPreviewByPageID(flagDownPage);  
			}
		}
		flagDownPage=null; 
		uicScrollViewIsDown = false; 
		$("#"+id).css("cursor","default"); 
		e.preventDefault(); 
		e.stopPropagation();
	});
	container.addEventListener('mousemove', e=> {
		if (!uicScrollViewIsDown) return; 
		const x = e.pageX - container.offsetLeft;
		const walk = (x - uicScrollViewStartX) * 2;
		container.scrollLeft = uicScrollViewLeft - walk;
		// var w1 = sb01.GetContentWidth();
		// var w2 = sb01.GetParentWidth();
		var maxpos = sb01.GetMaxScrollLeft();
		sb01.SetPositionF(container.scrollLeft / maxpos);
		//console.log("currentScroll:", container.scrollLeft, w1-w2);
	});
	return true;
}

function DocumentScrollXByWheel(){ 
	document.addEventListener('wheel', (e) => {
		//e.preventDefault(); 
		//e.stopPropagation();
		var d = e.deltaY; 
		document.scrollLeft += d; 
	});
	return true;
}
function ScrollXByWheel(id){ 
	if(!id){return false;}
	var container = document.getElementById(id);
	if(!container){return false;}
	container.addEventListener('wheel', (e) => {
		//e.preventDefault(); 
		//e.stopPropagation();
		var d = e.deltaY; 
		container.scrollLeft += d; 
	});
	return true;
}
DocumentScrollXByWheel();
ScrollXByLButtonDrag('pages');

function ZoomPreview(index){
	if(!index){index=0;}
	var p = _pages[index];
	if(!p){
		console.error("INVALID PAGE INDEX # ", index);
		return;
	}
	var xml = GeneratePage(_pages[index],'ZoomPreview');
	$(".ZoomPreview").html(xml);
	$(".PopupDialog").css("display","flex");
	UpdateImageRadius('ZoomPreview',0.95);
    $("#MajorPageZoomPreviewloading").css('display','flex');
    setTimeout(function(){
        $("#MajorPageZoomPreviewloading").css('display','none');
    },500);
	if(!p.upper){
		SetupAutoHideTopbar('ZoomPreview');
	}
    _zoomPreviewIndex = index;
}
var _flagZoomPreviewDialog;
var _zoomPreviewIndex=0;
function Event_ZoomPreview_Next(e){
    if(_flagZoomPreviewDialog){
        var sum = pages.length;
        var i = _zoomPreviewIndex+1;
        if(i>=sum){i=0;}
        ZoomPreview(i);
    }
}
function Event_ZoomPreview_Prev(e){
    if(_flagZoomPreviewDialog){
        var sum = pages.length;
        var i = _zoomPreviewIndex-1;
        if(i<0){i=sum-1;}
        ZoomPreview(i);
    }
}
function CloseZoomPreview(){
    $('.PopupDialog').hide();
    _flagZoomPreviewDialog=false;
}
function Event_ZoomPreview(index){
    if(_flagZoomPreviewDialog){return;}
    _flagZoomPreviewDialog=true;
	console.log("OpenIndex:",index);
    var page = _pages[index]; 
	console.log(page);
    ZoomPreview(index);
}

document.addEventListener("keydown",e=>{
    var k = e.key;
    console.log("KeyDown:",e.key);
    if(k=="Escape"){
		CloseZoomPreview(); 
    }else if(k=="ArrowLeft"){
        Event_ZoomPreview_Prev(); 
    }else if(k=="ArrowRight"){
        Event_ZoomPreview_Next();
    }
});

function SwitchNav(index){
	var sum = nav.items.length;
	for(var i=0;i<sum;i++){
		if(i == index){
			$("#navitem"+i).addClass("NavItemActive");
		}else{
			$("#navitem"+i).removeClass("NavItemActive");
		}
	}
	OnSwitchProject(index);
	STORAGE.setInt('projectIndex',index);
}
function InitNav(){
	var xml='';
	var i=0;
	for(let x of nav.items){
		if(i == nav.active){
			xml+=`<div id='navitem${i}' onclick="SwitchNav(${i})" class="NavItem NavItemActive">${x.title}</div>`;
		}else{
			xml+=`<div id='navitem${i}' onclick="SwitchNav(${i})" class="NavItem">${x.title}</div>`;
		}
		i++;
	}
	$(".Nav").html(xml);
}


function Event_ContractMe(){
	$('.UIDialogPopup').css('display','flex');
}

function UpdateImageRadius(pageKey,heightVH){
	var props = CalcPageShowSize(heightVH);

	// var client = GetClientSize(); 
	// if(!heightVH){heightVH=0.7;}
	// var modelHeightReal = client.height * heightVH;
	// var modelWidthReal = modelHeightReal * (MODEL.width / MODEL.height);
	// var scale = modelHeightReal / MODEL.height;
//	var rateBr = MODEL.pageBorderRadius / MODEL.width;
	
	//console.log("ModelRealSize:",modelWidthReal, modelHeightReal);
	
	//var pageWidth = MODEL.width - MODEL.outerSpacing*2;
	//var pageWidthReal = pageWidth * scale;
//	console.log('pageWidthReal',pageWidthReal);

	var imgbr = props.pageShowWidth * (MODEL.pageBorderRadius / props.pageWidth) + 2;
	// console.log("imgbr:",imgbr);
	// var obj = $(".PhoneContent");
	// obj.css("border-radius",imgbr+'px');
	if(EFFECT_LEVEL == 0){
		imgbr *= 0.7;
	}
 
	if(pageKey=='all'){
		for(let p of pages){
			var id = "#PhoneContent"+p.index;
			$(id).css("border-radius",imgbr+'px');
		}
	}else{
		var id = "#PhoneContent"+pageKey;
		$(id).css("border-radius",imgbr+'px');
	} 
}